package com.leetcode.p0;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class Test40 {

    private List<List<Integer>> res   = new ArrayList<>();
    private Deque<Integer>      stack = new LinkedList<>();

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);

        dfs(candidates, target, 0, 0, 0);

        return res;
    }

    private void dfs(int[] candidates, int target, int begin, int limit, int sum) {
        if (sum == target) {
            res.add(new ArrayList<>(stack));
            return;
        }

        for (int i = begin; i < candidates.length; i++) {
            if (candidates[i] < limit) {
                continue;
            }

            if (i > begin && candidates[i] == candidates[i - 1]) {
                continue;
            }

            sum += candidates[i];

            if (sum > target) {
                return;
            }
            stack.addLast(candidates[i]);

            dfs(candidates, target, i + 1, candidates[i], sum);

            sum -= candidates[i];
            stack.removeLast();
        }
    }

    public static void main(String[] args) {
        Test40 test = new Test40();
        System.out.println(test.combinationSum2(new int[]{10, 1, 2, 7, 6, 1, 5}, 8));
//        System.out.println(test.combinationSum2(new int[]{1, 2}, 4));
    }

}
